package models

import (
	"time"

	"github.com/beego/beego/v2/client/orm"
)

// Favorite 用户收藏门店模型
type Favorite struct {
	BaseModel
	UserId  int64 `orm:"column(user_id)" json:"user_id"`   // 用户ID
	StoreId int64 `orm:"column(store_id)" json:"store_id"` // 门店ID
	Status  int8  `orm:"column(status)" json:"status"`     // 状态：1正常，0取消收藏
}

// TableName 指定表名
func (f *Favorite) TableName() string {
	return "favorite"
}

// AddFavorite 添加收藏
func AddFavorite(userId, storeId int64) (int64, error) {
	o := orm.NewOrm()

	// 查询是否已经收藏过
	var favorite Favorite
	err := o.QueryTable(new(Favorite)).
		Filter("user_id", userId).
		Filter("store_id", storeId).
		Filter("is_deleted", 0).
		One(&favorite)

	// 如果已存在收藏记录
	if err == nil {
		// 如果状态为取消收藏，则恢复收藏状态
		if favorite.Status == 0 {
			favorite.Status = 1
			favorite.UpdatedAt = time.Now().Unix()
			_, err := o.Update(&favorite, "status", "updated_at")
			return favorite.Id, err
		}
		// 如果状态为已收藏，则直接返回
		return favorite.Id, nil
	}
	favorite.BeforeInsert()
	favorite = Favorite{
		UserId:  userId,
		StoreId: storeId,
		Status:  1, // 1 表示正常收藏
	}

	return o.Insert(&favorite)
}

// CancelFavorite 取消收藏
func CancelFavorite(userId, storeId int64) error {
	o := orm.NewOrm()

	// 查询收藏记录
	var favorite Favorite
	err := o.QueryTable(new(Favorite)).
		Filter("user_id", userId).
		Filter("store_id", storeId).
		Filter("status", 1).
		Filter("is_deleted", 0).
		One(&favorite)

	if err != nil {
		return err
	}

	// 更新为取消收藏状态
	favorite.Status = 0
	favorite.UpdatedAt = time.Now().Unix()
	_, err = o.Update(&favorite, "status", "updated_at")
	return err
}

// GetUserFavorites 获取用户收藏列表
func GetUserFavorites(userId int64, page, pageSize int) ([]*Favorite, int64, error) {
	o := orm.NewOrm()

	var favorites []*Favorite
	qs := o.QueryTable(new(Favorite)).
		Filter("user_id", userId).
		Filter("status", 1).
		Filter("is_deleted", 0).
		OrderBy("-created_at")

	// 计算总数
	total, err := qs.Count()
	if err != nil {
		return nil, 0, err
	}

	// 分页查询
	_, err = qs.Limit(pageSize, (page-1)*pageSize).All(&favorites)
	if err != nil {
		return nil, 0, err
	}

	return favorites, total, nil
}

// IsFavorite 判断是否已收藏
func IsFavorite(userId, storeId int64) (bool, error) {
	o := orm.NewOrm()

	// 查询收藏记录
	count, err := o.QueryTable(new(Favorite)).
		Filter("user_id", userId).
		Filter("store_id", storeId).
		Filter("status", 1).
		Filter("is_deleted", 0).
		Count()

	if err != nil {
		return false, err
	}

	return count > 0, nil
}
